package cn.kgc.utils;

import cn.kgc.reflect.Person;
import cn.kgc.reflect.Student;

import java.lang.reflect.Constructor;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/2/14
 * @Description: 对象工厂
 */
public class BeanFactory {

    public  static  Object getBean(String path){

        try {

            Class clazz = Class.forName(path);
            Constructor declaredConstructor = clazz.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            Object o = declaredConstructor.newInstance();
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    public  static  <T>  T  getBean(String path,Class<T> claz){

        try {

            Class clazz = Class.forName(path);

            Constructor declaredConstructor = clazz.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            Object o = declaredConstructor.newInstance();

            return  claz.cast(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }


    public static void main(String[] args) {

        //Student student = (Student) getBean("cn.kgc.reflect.Student");
        Student student = getBean("cn.kgc.reflect.Student", Student.class);
        System.out.println("student = " + student);
    }

}
